#include "main.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <fcntl.h>

/* Global variables */
static char userInput = '\0';
static char buffer[BUFFER_MAX_LENGTH];
static int bufferChars = 0;

//static char *commandArgv[5];
static int commandArgc = 0;
static int dollar_pipe_pos[10],dollar_pipe_len,no_of_dollar_pipes;
static int outFile_pos,outFile_len;


char **cmd_list;

static struct symbolTable ST[NO_OF_SYMBOL];
static int countOfSymbol = 0;

/*******************************************************************************
  * Function Name: main
  *
  ******************************************************************************/
int main(int argc, char*argv[])
{
	int rc;
	int i;
	int symbolFound = 0;
	// Max number of shell arguments is 18 
	cmd_list = (char **) malloc(18*sizeof(char *));

    	// parser should give back cmd_list
    	for(i=0;i<18;i++){
        	cmd_list[i] = NULL;
    	}	
		
	/* Register signal handler */
	register_signal_handler();

	/* Read the profile file and sets env etc. */
	readProfile();

	/* Welcome the user */
	welcomeUser();
	//printf("Path is %s \n",getenv("PATH"));

	/* Dispaly the prompt */
	shellPrompt();

	readSymbolFromFile();

	while(TRUE)
	{
		userInput = getchar();
		switch (userInput)
		{	
			case '\n':
				shellPrompt();				
				break;
			default:
				ReadLineFromUser();
				if(isRegExpr())
				{
                  			switch(parseIntCommand())
					{
                    			case 0:
                 				storeSymbol();
                        		break;
                       			case 1:
	         				solveRegExpr();
	                       			break;
                        		case 2:
						symbolFound = findSymbol(&buffer[0]);					
						if(symbolFound == ERR)
		                        		printf("variable not found. \n");
						else
							printf("%c = %d \n",buffer[1],symbolFound);
						break;
                   			}
            			}
				else
            			{
					fillCommand();
					processCmds();
				}
				shellPrompt();
				break;
		}
	}
    printf("\n");	
    return 0; 
}

/*******************************************************************************
  * Function Name: isRegExpr
  *
  ******************************************************************************/

int isRegExpr()
{

	if(strstr(buffer,"SLV") != NULL || strstr(buffer,"STR") != NULL || buffer[0] == '$')
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

/*******************************************************************************
  * Function Name: parseIntCommand
  *
  ******************************************************************************/

int parseIntCommand()
{
	if(strncmp(buffer,"SLV",3) == 0)
		return 1;
	else if(strncmp(buffer,"STR",3) == 0)
		return 0;
	else if(buffer[0] == '$')
		return 2;

	return 100;
}

/*******************************************************************************
  * Function Name: storeSymbol
  *
  ******************************************************************************/

int storeSymbol(){
	char *ch;
	ch = strtok(buffer," ");
	ch = strtok(NULL," ");

	int index = 0;
	// Variable name check added
	if(ch == NULL || (void *)*(ch+1) != NULL)
	{
		printf("\n Not correct variable name. \n");
		return ERR;
	}
	/* Check if the symbol is present or not , if yes replace its value */
	 
	index = checkSymbol(ch);
	 
	if( index != ERR){
		ch = strtok(NULL," ");	// Symbol found
		if(ch != NULL){
			ST[index].value = atoi(ch); // updating its value
			return 1;
		}else{
			return 0;
		}
	}

	/* Symbol is not there so adding new one */

	if((ch != NULL) || (*ch >= 'A' && *ch <= 'Z') || (*ch >= 'a' && *ch <= 'z')){
		ST[countOfSymbol].symbol = *ch;
		ch = strtok(NULL," ");
		if(ch != NULL)
		{
			ST[countOfSymbol].value = atoi(ch);
			countOfSymbol++;
			return 1;
		}
		else
		{
			printf("\n Not correct variable name. ");
			return 0;
		}

	}else{
		printf("\n Not correct variable name. ");
		return 0;
	}
}

/*******************************************************************************
  * Function Name: solveRegExpr
  *
  ******************************************************************************/
void solveRegExpr()
{

	char *ch;
	int op1, op2, result;
	int symValue = 0;

	if(isValidExprn() == 0)
	{
		printf("\n Not a valid expression.\n");
		return;
	}

	resetStack();
	ch = strtok(buffer," ");

	while(ch != NULL)
	{
		if(strcmp(ch,"SLV") == 0)
		{

		}
		else if(*ch == '+')
		{
			op1 = pop();
			op2 = pop();

			if(op1 == ERR || op2 == ERR)
			{
				printf("not enought Arg \n");
				return;
			}
			else
			{
				result = op1 + op2;
			}
			push(result);
		}
		else if(*ch == '-')
		{
			op2 = pop();
			op1 = pop();
			if(op1 == ERR || op2 == ERR)
			{
				printf("not enought Arg \n");
				return;
			}
			else
			{
				result = op1 - op2;
			}
			push(result);
		}
		else if(*ch == '*')
		{
			op1 = pop();
			op2 = pop();
			if(op1 == ERR || op2 == ERR)
			{
				printf("not enought Arg \n");
				return;
			}
			else
			{
				result = op1 * op2;
			}
			push(result);
		}
		else if(*ch == '/')
		{
			op2 = pop();
			op1 = pop();
			if(op1 == ERR || op2 == ERR)
			{
				printf("not enought Arg \n");
				return;
			}
			else
			{
				result = op1 / op2;
			}
			push(result);
		}
		else if((*ch == '(') || (*ch == ')'))
		{

		}
		else if(*ch == '$')
		{
			symValue = findSymbol(ch);
			if(symValue == ERR)
			{
				printf("Variable Not Found \n");
				return;
			}
			push(symValue);
		}
		else
		{
			push(atoi(ch));
		}
		ch = strtok(NULL," ");
	}

	result = pop();
	if(pop() != ERR)
		printf("\n Something wrong.\n");
	else
		printf(" = %d \n",result);

}

/*******************************************************************************
  * Function Name: isValidExprn
  *
  ******************************************************************************/

int isValidExprn()
{
	char *ch;
	resetStack();
	if((strchr(buffer,'+') != NULL) || (strchr(buffer,'-') != NULL) ||
		(strchr(buffer,'*') != NULL) || (strchr(buffer,'/') != NULL ))
	{

		 if(strchr(buffer,'(') != NULL || strchr(buffer,')') != NULL)
		 {
			ch = &buffer[0];
				
			while((void *)*ch != NULL)
			{
				
				if(*ch == '(')
					push(*ch);
				if(*ch == ')'){
					if(pop() == ERR)
						return 0;
				}
				
				ch++;
			} 
			if(pop() != ERR)
			{
				return 0;
			}
		 }

		if(buffer[bufferChars-1] == ')') 
		{
			if(buffer[bufferChars-3] == '+' || buffer[bufferChars-3] == '-'
				|| buffer[bufferChars-3] == '*' || buffer[bufferChars-3] == '/')
			{
					return 1;
			}
	    }
		else if(buffer[bufferChars-1] == '+' || buffer[bufferChars-1] == '-'
				|| buffer[bufferChars-1] == '*' || buffer[bufferChars-1] == '/')
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	return 0;
}

/*******************************************************************************
  * Function Name: findSymbol
  *
  ******************************************************************************/
int findSymbol(char *ch)
{
	int i = 0;
	ch++;
	while(i != countOfSymbol)
	{
		if(*ch == ST[i].symbol)
			return (ST[i].value);

		i++;
	}

	if(i == countOfSymbol)
		return ERR;
	else
		return 100;//to remove warning
}

/*******************************************************************************
  * Function Name: checkSymbol
  *
  ******************************************************************************/


int checkSymbol(char *ch)
{
	int i = 0;

	while(i != countOfSymbol)
	{
		if(*ch == ST[i].symbol)
			return i;	// symbol found at inidex i
		i++;
	}

	if(i == countOfSymbol)
	{	return ERR; } // unable to find symbol

	return 0;
}

/*******************************************************************************
  * Function Name: writeSymbolToFile
  *
  ******************************************************************************/

void writeSymbolToFile()
{
	FILE *fp;
	int i = 0;
	/* Read the profile file and set the required environment variables */

	fp = fopen(SYMBOL_FILE_NAME,"w");
	if (fp == NULL) 
	{
		// removed unnecessary printf
		return;
	}

	fprintf (fp, "%d \n",countOfSymbol);
	if(countOfSymbol != 0)
	{
		while(i < countOfSymbol)
		{
			fprintf (fp, "%c %d \n",ST[i].symbol,ST[i].value);
			i++;
		}
	}
	if (fp != NULL) 
	{
		    fclose(fp);
	}
}

/*******************************************************************************
  * Function Name: readSymbolFromFile
  *
  ******************************************************************************/

void readSymbolFromFile()
{
	FILE *fp;
	int i,j;
	/* Read the profile file and set the required environment variables */

	fp = fopen(SYMBOL_FILE_NAME,"r");
	if (fp == NULL) 
	{
		// removed unnecessary printf
		return;
	}
	j = 0;
	fscanf(fp,"%d \n",&i);
	countOfSymbol = i;
	if(countOfSymbol != 0)
	{
		while(fscanf (fp, "%c %d \n",&ST[j].symbol,&ST[j].value) != EOF)
		{
			if(j != i)
			{
				j++;
			}
		}
	}

	if (fp != NULL)
	{
		    fclose(fp);
	}
}

/*******************************************************************************
  * Function Name: ReadLineFromUser
  *
  ******************************************************************************/
void ReadLineFromUser(void)
{
	clearPrevCmd();
	while ((userInput != '\n') && (bufferChars < BUFFER_MAX_LENGTH)) {
			buffer[bufferChars++] = userInput;
			userInput = getchar();
	}
	buffer[bufferChars] = 0x00;	
	// fillCommand();
}

/*******************************************************************************
  * Function Name: clearPrevCmd
  *
  ******************************************************************************/
void clearPrevCmd()
{
	while (commandArgc != 0) 
	{
		//commandArgv[commandArgc] = NULL;
		cmd_list[commandArgc] = NULL;//MANI
		commandArgc--;
	}
	bufferChars = 0;
}

/*******************************************************************************
  * Function Name: fillCommand
  *
  ******************************************************************************/
void fillCommand()
{
	char* bufferPointer;
	char* p;

/* Added to replace double quotes with space: useful in grep */
#if 1
	p = &buffer[0];
	while ( (p=strstr(p,"\"")) != NULL )
	{
		strncpy(p," ",1);
	}
#endif

	bufferPointer = strtok(buffer, " ");
	while (bufferPointer != NULL)
	{
		//commandArgv[commandArgc] = bufferPointer;
		cmd_list[commandArgc] = bufferPointer;
		bufferPointer = strtok(NULL, " ");
		commandArgc++;
	}
}


/*******************************************************************************
  * Function Name: processCmds
  *
  ******************************************************************************/
void processCmds(void)
{	
	int len;
	if (strlen(cmd_list[0]) == 1) {
              	cmd_list[0]="true"; // hack for signal bug - Shaik
       	}
#if 0
	printf("Command list \n");
	len = 0;
	while(cmd_list[len]!=NULL)
	{
		printf("cmd[%d] =%s \n",len,cmd_list[len]);
		len++;
	}
#endif	

	if (strcmp("exit", cmd_list[0]) == 0) 
	{
		writeSymbolToFile();
		exit(EXIT_SUCCESS);
	}
	else if (strcmp("cd", cmd_list[0]) == 0) 
	{
		changeDir();
	}
	else if(pipeSearch() == PIPE_FOUND)
	{
		exePipe();
	}
	else if (dollarPipeSearch() == FOUND)
	{
		exeReversePipe();
	}

	else if(outFileSearch() == MULTIPLE_OUT_FOUND)
	{
		printf("The shell does not support commands with multiple redirection\n");
	}		
	else if(outFileSearch() == SINGLE_OUT_FOUND)
	{
		exeOutRedirection();
	}
	else
	{
		exeSingleCmd();
	}
}

/*******************************************************************************
  * Function Name: exeSingleCmd
  *
  ******************************************************************************/
void exeSingleCmd()
{
	int pid,status;
	int ret_val;
	char tmp[50];
	char *t[50];
	int i;

	// printf("exeSingleCmd: %s \n",tmp);
	
	pid = fork();
	if(pid == -1 ) 
	{
		perror("fork_error:");
		exit(EXIT_FAILURE);
	}
	else if(pid != 0) 
	{
		/* Parent process */
		waitpid(-1,&status,0);
		if(!(WIFEXITED(status)) )
			printf("Child %d NOT exited properly\n",pid);
	}
	else
	{
		ret_val = execvp(cmd_list[0],cmd_list);
		if(ret_val == -1) {
			perror("execution error:");
			exit(0);
		}
	}
}

/*******************************************************************************
  * Function Name: changeDir
  *
  ******************************************************************************/
void changeDir()
{
    	if (cmd_list[1] == NULL) 
	{
		chdir(getenv("HOME"));
    	} 
	else 
    	{
        	if (chdir(cmd_list[1]) == -1) 
		{
			printf(" %s: no such directory\n", cmd_list[1]);
        	}
    	}
}

/*******************************************************************************
  * Function Name: pipeSearch
  *
  ******************************************************************************/
ret_pipes pipeSearch()
{
	int index;
    char *pt;

    index = 0;
    dollar_pipe_len =0;
    no_of_dollar_pipes=0;

    for (int i =0; i<10;i++) 
	{
   		dollar_pipe_pos[i]=-1;
    }
	
    while(cmd_list[dollar_pipe_len] != NULL) 
    	dollar_pipe_len++;

    //     printf("\n Length of command list is %d \n", dollar_pipe_len);

    while(index < dollar_pipe_len)
    {
 //   	 printf ("Verifying the token %s \n" , cmd_list[index]);
       	pt=strstr(cmd_list[index],"|");
        if( pt != NULL )
        {
        	dollar_pipe_pos[no_of_dollar_pipes] = index;
                no_of_dollar_pipes++;
        }

        index++;
   }
   	if(no_of_dollar_pipes > 0)
	{
 //  		 printf ("\n number of dollar pipes found is %d \n", no_of_dollar_pipes);
   		for (int i =0; i<10;i++) 
		{
 //	              printf("dollar pipe pos is %d \n",dollar_pipe_pos[i]);
        }
     	return PIPE_FOUND;
     }
  	return PIPE_NOT_FOUND;
}

/*******************************************************************************
  * Function Name: outFileSearch
  *
  ******************************************************************************/
ret_outFiles outFileSearch(void)
{
	int index,no_of_outFile;
	char *pt;

	index = 0;
	outFile_len =0;
	no_of_outFile=0;
	
	while(cmd_list[outFile_len] != NULL) 
        outFile_len++;
	
	while(index < outFile_len)
	{
		pt=strstr(cmd_list[index],">");
		if( pt != NULL )
		{
			outFile_pos = index;
			no_of_outFile++;
		}

		index++;
	}

	if(no_of_outFile > 1)
		return MULTIPLE_OUT_FOUND;
	else if(no_of_outFile == 1)
		return SINGLE_OUT_FOUND;
	else
		return OUT_NOT_FOUND;

}

/*******************************************************************************
* Function Name: dollarPipeSearch
*
 ******************************************************************************/
ret_dollarpipes dollarPipeSearch()
{
	int index;
    char *pt;

    index = 0;
    dollar_pipe_len =0;
    no_of_dollar_pipes=0;

    for (int i =0; i<10;i++) 
	{
   		dollar_pipe_pos[i]=-1;
    }
	
    while(cmd_list[dollar_pipe_len] != NULL) 
    	dollar_pipe_len++;

    //     printf("\n Length of command list is %d \n", dollar_pipe_len);

    while(index < dollar_pipe_len)
    {
 //   	 printf ("Verifying the token %s \n" , cmd_list[index]);
       	pt=strstr(cmd_list[index],"$(");
        if( pt != NULL )
        {
        	dollar_pipe_pos[no_of_dollar_pipes] = index;
                no_of_dollar_pipes++;
        }

        index++;
   }
   	if(no_of_dollar_pipes > 0)
	{
 //  		 printf ("\n number of dollar pipes found is %d \n", no_of_dollar_pipes);
   		for (int i =0; i<10;i++) 
		{
 //	              printf("dollar pipe pos is %d \n",dollar_pipe_pos[i]);
        }
     	return FOUND;
     }
  	return NOT_FOUND;
}


/*******************************************************************************
  * Function Name: exeReversePipe
  *
  ******************************************************************************/
void exeReversePipe(void)
{
	int pid,i,j,k,status;
	int cmd_pos=0;
	int n = no_of_dollar_pipes + 1 ;
	char ***args = (char ***)malloc(n * sizeof(char**)) ;
	char ***reverse_args = (char ***)malloc(n * sizeof(char**)) ;
	int ret_val=0;

	for(i = 0 ; i < n ; i++ )
	{ 
		args[i] = (char ** ) malloc(10 * sizeof(char * )) ;
	}

	for (i =0; i < n; i++ ) 
	{
		reverse_args[i] = (char ** ) malloc(10 * sizeof(char * )) ; 
	}

	/* Populating arguments for each command */
	
	for (i = 0; i < n; i++)  
	{
		k=0;
		if (dollar_pipe_pos[i] != -1 ) 
		{
			for(;cmd_pos<dollar_pipe_pos[i];cmd_pos++)
			{
//				printf(" print cmd list %s \n", cmd_list[cmd_pos]);
         			if((strcmp(cmd_list[cmd_pos],"$")!=0) && (strcmp(cmd_list[cmd_pos],")")!=0) && (strcmp(cmd_list[cmd_pos],"$(")!=0)) 
				{
					args[i][k] = cmd_list[cmd_pos];
					k++;
				}
			}
		}
		else 
		{
			for(;cmd_pos<dollar_pipe_len;cmd_pos++)
			{
//                          	printf(" END print cmd list %s \n", cmd_list[cmd_pos]);
		        	if((strcmp(cmd_list[cmd_pos],"$")!=0) && (strcmp(cmd_list[cmd_pos],")")!=0) && (strcmp(cmd_list[cmd_pos],"$(")!=0)) 
				{
	            			args[i][k] = cmd_list[cmd_pos];
	                		k++;
		        	}
			}
		}
		args[i][k]=0x00;

	}


#if 0
	for(i=0;i<n;i++) 
	{
		int m=0;
		while(args[i][m]!='\0')
		{
			printf("PrintArg%d = %s\n",i,args[i][m]);
			m++;
		}
	}           
#endif



		/* Reverse the array */
#if 1
	for(j=n-1,i=0;j>=0;j--,i++) 
	{
		int m=0;
	    	while(args[j][m]!='\0')
		{
			reverse_args[i][m]=args[j][m];
//	      		printf("ReversePrintArg%d = %s\n",i,reverse_args[i][m]);
           		m++;
        	}
        	reverse_args[i][m]=0x00;
	}

#endif 


#if 0
    	for(i=0;i<n;i++) 
	{
        	int m=0;
        	while(reverse_args[i][m]!='\0')
		{
            		printf("ReverseArg%d = %s\n",i,reverse_args[i][m]);
            		m++;
        	}
    	}           
#endif

#if 1
	/* Create pipes */
	int pipe_in[2];
   	int pipe_out[2];

  	if((pipe(&pipe_in[0])) == -1 ) 
    	{
      		perror("pipe_error:");
           	return;
   	}  

//    	printf("n  is equal to %d \n",n);

	for( i=0;i<n; i++)
	{
//		printf("i  is equal to %d \n",i);
		pid = -1;
		status = 0;
		if((pipe(&pipe_out[0])) == -1 ) 
		{
			perror("pipe_error:");
		       	return;
        	}  

		pid = fork();

		if ( pid < 0 ) 
		{
			perror("forking_error:");
		 	exit(0);
		}
		else if(pid == 0) 
		{
			 // If it is not the first program, then setup incoming pipe
			 if(i!=0)
			 {
               			close( pipe_in[1] );       
		        	dup2( pipe_in[0], 0 );    
		        	close( pipe_in[0] );     
			 }
			 else
			 {
		       		close( pipe_in[0] ); 
		       		close( pipe_in[1] );
			 }

			 // If it is not the last program, then setup outgoing pipe 
			 if(i!=n-1)
			 {
			 	close( pipe_out[0] );         
			 	dup2( pipe_out[1], 1); 
			 	close( pipe_out[1] ); 
			 }
			 else
			 {
			 	close( pipe_out[0] );
			 	close( pipe_out[1] );
		 	 }

		 	 // ret_val= execvp(args[i][0],args[i]);
		 	 ret_val= execvp(reverse_args[i][0],reverse_args[i]);
		 	 if(ret_val == -1)
			 {
		 	       // printf("%s: not found \n",args[i][0]);
		 	       printf("%s: not found \n",reverse_args[i][0]);
		 	       exit(0);
		 	 }
		}

		// Make pipe_in  now pipe_out  
		dup2(pipe_out[0],pipe_in[0]);
		dup2(pipe_out[1],pipe_in[1]);     


		close(pipe_out[0]);
		close(pipe_out[1]);
		fflush(stdout);
    	}    
	close(pipe_in[1]);
	close(pipe_in[0]);

	for(i=0;i<n;i++)
	{
	   waitpid(-1,NULL,0);
	}

#endif
}


/*******************************************************************************
  * Function Name: exePipe
  *
  ******************************************************************************/

void exePipe(void)
{
	int pid,i,j,k,status;
	int cmd_pos=0;
	int n = no_of_dollar_pipes + 1 ;
	char ***args = (char ***)malloc(n * sizeof(char**)) ;

	int ret_val=0;

	for(i = 0 ; i < n ; i++ )
	{ 
		args[i] = (char ** ) malloc(10 * sizeof(char * )) ;
	}

	
	/* Populating arguments for each command */
	
	for (i = 0; i < n; i++)  
	{
		k=0;
		if (dollar_pipe_pos[i] != -1 ) 
		{
			for(;cmd_pos<dollar_pipe_pos[i];cmd_pos++)
			{
//				printf(" print cmd list %s \n", cmd_list[cmd_pos]);
         			if((strcmp(cmd_list[cmd_pos],"|")!=0)&& (strcmp(cmd_list[cmd_pos],"$")!=0) && (strcmp(cmd_list[cmd_pos],")")!=0) && (strcmp(cmd_list[cmd_pos],"$(")!=0)) 
				{
					args[i][k] = cmd_list[cmd_pos];
					k++;
				}
			}
		}
		else 
		{
			for(;cmd_pos<dollar_pipe_len;cmd_pos++)
			{
//                          	printf(" END print cmd list %s \n", cmd_list[cmd_pos]);
		        	if((strcmp(cmd_list[cmd_pos],"|")!=0)&&(strcmp(cmd_list[cmd_pos],"$")!=0) && (strcmp(cmd_list[cmd_pos],")")!=0) && (strcmp(cmd_list[cmd_pos],"$(")!=0)) 
				{
	            			args[i][k] = cmd_list[cmd_pos];
	                		k++;
		        	}
			}
		}
		args[i][k]=0x00;

	}


#if 0
	for(i=0;i<n;i++) 
	{
		int m=0;
		while(args[i][m]!='\0')
		{
			printf("PrintArg%d = %s\n",i,args[i][m]);
			m++;
		}
	}           
#endif

		
#if 1
	/* Create pipes */
	int pipe_in[2];
   	int pipe_out[2];

  	if((pipe(&pipe_in[0])) == -1 ) 
    	{
      		perror("pipe_error:");
           	return;
   	}  

//    	printf("n  is equal to %d \n",n);

	for( i=0;i<n; i++)
	{
//		printf("i  is equal to %d \n",i);
		pid = -1;
		status = 0;
		if((pipe(&pipe_out[0])) == -1 ) 
		{
			perror("pipe_error:");
		       	return;
        	}  

		pid = fork();

		if ( pid < 0 ) 
		{
			perror("forking_error:");
		 	exit(0);
		}
		else if(pid == 0) 
		{
			 if(i!=0)
			 {
               			close( pipe_in[1] );       
		        	dup2( pipe_in[0], 0 );    
		        	close( pipe_in[0] );     
			 }
			 else
			 {
		       		close( pipe_in[0] ); 
		       		close( pipe_in[1] );
			 }

			 if(i!=n-1)
			 {
			 	close( pipe_out[0] );         
			 	dup2( pipe_out[1], 1); 
			 	close( pipe_out[1] ); 
			 }
			 else
			 {
			 	close( pipe_out[0] );
			 	close( pipe_out[1] );
		 	 }

		 	 ret_val= execvp(args[i][0],args[i]);
		 	 if(ret_val == -1)
			 {
		 	       printf("%s: not found \n",args[i][0]);
		 	       exit(0);
		 	 }
		}

		dup2(pipe_out[0],pipe_in[0]);
		dup2(pipe_out[1],pipe_in[1]);     


		close(pipe_out[0]);
		close(pipe_out[1]);
		fflush(stdout);
    }    
	close(pipe_in[1]);
	close(pipe_in[0]);

	for(i=0;i<n;i++)
	{
	   waitpid(-1,NULL,0);
	}

#endif
}



/*******************************************************************************
  * Function Name: exeOutRedirection
  *
  ******************************************************************************/
void exeOutRedirection()
{
	int i,j,k,status,pid;	
	int out_fd;
	char **arg1;
	char **arg2;
	int ret_val=0;

	arg1 = (char **) malloc(10*sizeof(char *));
	arg2 = (char **) malloc(10*sizeof(char *));

	/* Populating argument 1 */
	for(i=0;i<outFile_pos;i++)
		arg1[i] = cmd_list[i];	
	arg1[i] = 0x00; 
#if 0
	for(j=0;j<i;j++)
		printf("Arg1 = %s\n",arg1[j]);
#endif

	/* Populating argument 2 */
	for(k=0,i=outFile_pos+1;i<outFile_len;i++,k++)
		arg2[k] = cmd_list[i];
	arg2[k] = 0x00; 	
#if 0
	for(j=0;j<k;j++)
		printf("Arg2 = %s\n",arg2[j]);
#endif	

	pid = fork();
	if(pid == -1 ) 
	{
		perror("fork_error:");
		exit(EXIT_FAILURE);
	}
	else if(pid != 0) 
	{
		/* Parent process */
		waitpid(-1,&status,0);
		if(!(WIFEXITED(status)) )
			printf("Child %d NOT exited properly\n",pid);
	}
	else
	{
		/* Child process */
		out_fd = open(arg2[0],O_CREAT | O_TRUNC | O_RDWR,S_IRUSR |S_IWUSR);
		if(out_fd == -1 ) 
		{
			perror("error_redirect:");
			return;
		}
		close(STD_OUTPUT);
		dup(out_fd);
		close(out_fd);
		ret_val = execvp(arg1[0],arg1);
		if(ret_val == -1)
			perror("execution error:");
	}
}

/*******************************************************************************
 * End of file
 */

